<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class mpost extends MY_Model {

    var $theme_data = array(
        'layout_main' => 'layout',
        'left' => 'include/leftcp',
    );
    public $mytable = "post";
    public $primaryKey = "pos_id";
    public $resCode = "LIST_POST";

    function __construct() {
        parent::__construct();
    }

    function field() {
        $fieldData = array();
        $fieldData['pos_title'] = '';        
        $fieldData['pos_code'] = '';
        $fieldData['pos_alias'] = '';
        $fieldData['pos_image'] = '';
        $fieldData['pos_image2'] = '';
        $fieldData['pos_snippet'] = '';
        $fieldData['pos_content'] = '';
        $fieldData['pos_relate'] = '';
        $fieldData['pos_date_create'] = time();
        $fieldData['pos_date_update'] = time();
        $fieldData['pos_user_create'] = 0;
        $fieldData['pos_status'] = -2;
        $fieldData['seo_h1'] = '';
        $fieldData['seo_description'] = '';
        $fieldData['seo_title'] = '';
        $fieldData['seo_keyword'] = '';
        $fieldData['pos_date_start'] = time();
        $fieldData['seo_keyword_image'] ='';
        $fieldData['pos_source'] = '';
        $fieldData['pos_count_view'] = 0;
        return $fieldData;
    }

    function update_view($post_id = 0) {
        //update view
        $this->db->where("pos_id", $post_id);
        $this->db->set('pos_count_view', 'pos_count_view+1', false);
        $this->db->update($this->mytable, array());
    }

    function delete($post_id) {
// 	    var_dump($post_id);
        $this->db->delete($this->mytable, array($this->primaryKey => $post_id));
    }

    public function no_update_field($data) {
        $fields = array(
            'pos_count_view',
            'pos_count_loaded',
            'pos_user_create',
            'pos_date_create',
        );
        if ($data)
            foreach ($data as $i => $item) {
                if (in_array($i, $fields)) {
                    unset($data[$i]);
                }
            }
        return $data;
    }

    /*
      $permission_code:
      'list_post', 'approve_post', 'person_list_post',
     */

    function permission($permission_code, $admin_id = 0) {
        $flag = 0;
        switch ($permission_code) {
            case 'list_post':
                $flag = ($this->permission->check("insert", $this->resCode) ||
                        $this->permission->check("update", $this->resCode) ||
                        $this->permission->check("delete", $this->resCode));
                break;
            case 'approve_post':
                $flag = $this->permission->check("select", $this->resCode);
                break;
            case 'person_list_post':
                $flag = ($this->permission->check("insert", $this->resCode) ||
                        $this->permission->check("update", $this->resCode) ||
                        $this->permission->check("delete", $this->resCode));
                break;
        }
        return $flag;
    }

    //Front end Function 
    public function get_post($post_id) {
        $this->db->where_in('pos_id', $post_id);
        $this->db->order_by('pos_id');
        return $this->get();
    }

    public function get_posts($posts){
        $this->db->where_in('pos_id', $posts);
        $this->db->order_by('pos_id');
        return $this->gets();   
    }



    // Post other
    public function get_post_other($ids, $postid = 0) {
        $this->db->_protect_identifiers = FALSE;
        $this->db->where('pos_status >', '0');
        if ($ids)
            $this->db->where_in('pos_id', $ids);
        if ($postid)
            $this->db->where('pos_id <>', $postid);

        $this->db->order_by('pos_date_start', 'desc');
        // if($ids)
        // 	$this->db->order_by("FIELD(pos_id, ".implode(',', $ids).")");
        $this->db->_protect_identifiers = TRUE;
        return $this->gets();
    }

    

    // Post other
    public function get_post_relate($ids, $postid = 0, $limit = 6) {
        $this->db->where('pos_status >', '0');
        if ($ids)
            $this->db->where_in('pos_id', $ids);
        if ($postid) {
            $this->db->where('pos_id <>', $postid);
            $this->db->where('pos_id <', $postid);
        }
        $this->db->order_by('pos_date_start desc');
        $this->db->limit($limit);
        // if($ids)
        // 	$this->db->order_by("FIELD(pos_id, ".implode(',', $ids).")");
        return $this->gets();
    }

    // get_view_most_post()
    public function get_view_most_post($ids) {
        $this->db->_protect_identifiers = FALSE;
        $this->db->join('post_category', 'post_category.pos_id = post.pos_id');
        $this->db->where('post.pos_status >', '0');
        $this->db->where_in('post_category.cat_id', $ids);
        $this->db->order_by('post.pos_count_view desc');
        $this->db->limit(10);
        $this->db->_protect_identifiers = TRUE;
        return $this->gets();
    }

    public function get_post_event($event_id){
        $this->db->_protect_identifiers = FALSE;
        $this->db->join('post_event', 'post_event.post_id = post.pos_id');
        $this->db->where('post.pos_status >', '0');
        $this->db->where('post_event.event_id',$event_id);
        $this->db->order_by('post.pos_count_view desc');
        $this->db->_protect_identifiers = TRUE;
        return $this->gets();   
    }

// end get_view_most_post
    
//get_relate_post()
    public function gets_relate_post($ids, $postid = 0,$limit = 6) {
        $this->db->where('post.pos_date_start <',time());
        $this->db->order_by('post.pos_date_start desc');
        $this->db->where('post.pos_status >', '0');
        if ($ids)
            $this->db->where_in('pos_id', $ids);
        if ($postid)
            $this->db->where('pos_id <>', $postid);
        $this->db->_protect_identifiers = FALSE;
        if ($ids)
            $this->db->order_by("FIELD(pos_id, " . implode(',', $ids) . ")");
        $this->db->limit($limit)
                ->_protect_identifiers = TRUE;
        return $this->gets(); 
    }
// end get_relate_post()

    public function get_relate_post($ids) {
        if ($ids) {
            // $this->db->select('pos_id, pos_title, pos_code');
            $this->db->where_in('pos_id', $ids);
            $this->db->_protect_identifiers = FALSE;
            $this->db->order_by("FIELD(pos_id, " . implode(',', $ids) . ")");
            $this->db->_protect_identifiers = TRUE;
            return $this->gets();
        }
        return null;
    }

    public function get_relate_post_by_tag($ids){
        $result = array();
        $posttags = $this->mposttag->gets($ids,'pos_id');
        if($posttags){
            $tagids = array();
            foreach ($posttags as $pt){
                $tagids[] = $pt->tag_id;
            }   
            $this->db->where('pos_id <>',$ids);
            $this->db->where_in('tag_id', $tagids);
            $this->db->group_by('pos_id');
            $this->db->limit(4);
            $post_ids = $this->mposttag->gets();

            if($post_ids){
                $pids = array();
                foreach ($post_ids as $p)  $pids[] = $p->pos_id;

                $this->db->select('pos_id,pos_title,pos_code,pos_image');
                $this->db->where_in('pos_id',$pids);
                $this->db->where('pos_status >',0);
                $this->db->limit(3);
                $result = $this->gets();
            }
        }
        return $result;
    }   

    // Get post follow category
    public function get_post_by_cate($id, $num, $type,$ignore_list=null) {
        if ($id) {
            $this->db->join('post_category', 'post_category.pos_id =' . $this->mytable . '.pos_id');
            $this->db->_protect_identifiers = FALSE;
            if ($num)
                $this->db->limit($num);
            if ($type)
                $this->db->order_by($type);
            $this->db->group_by('post.pos_id');
            $this->db->where('post.pos_status >', '0');
            $this->db->where_in('cat_id', $id);
            $this->db->_protect_identifiers = TRUE;
            return $this->gets();
        }
        return null;
    }

// end get_post_by_cate() function
    // Get post follow sub category
    public function get_post_by_subcate($id, $num, $type) {
        if ($id) {
            if ($num)
                $this->db->limit($num);
            if ($type)
                $this->db->order_by($type);
            $this->db->group_by('post.pos_id');
            $this->db->where('post.pos_date_start <',time());
            $this->db->where('post.pos_status >', '0');
            $this->db->join('post_category', 'post_category.pos_id =' . $this->mytable . '.pos_id');
            $this->db->_protect_identifiers = FALSE;
            $this->db->where('cat_id', $id);
            $this->db->_protect_identifiers = TRUE;
            return $this->gets();
        }
        return null;
    }

// end get_post_by_subcate() function
    // search 
    function search($terms, $config) {
        $this->db->select('pos_id, pos_code, pos_alias, pos_content,pos_snippet,pos_image, pos_status, pos_date_create, pos_date_start, pos_title');
        $this->db->like('pos_code', $terms);
        $this->db->or_like('pos_alias', str_replace("-", " ", $terms));
        $this->db->or_like('pos_title', str_replace("-", " ", $terms));
        $this->db->or_like('pos_snippet', str_replace("-", " ", $terms));
        $this->db->where('pos_status >', '0');
        $this->db->order_by('pos_id');
        return $this->mpost->pagination('', '', $config);
    }

// end search()

    function count_search_results($terms) {
        // $this->db->select('count(*)');
        $this->db->like('pos_code', $terms);
        $this->db->or_like('pos_alias', str_replace("-", " ", $terms));
        $this->db->or_like('pos_title', str_replace("-", " ", $terms));
        $this->db->or_like('pos_snippet', str_replace("-", " ", $terms));
        $this->db->or_like('pos_content', str_replace("-", " ", $terms));
        $this->db->where('pos_status >', '0');
        // $this->db->order_by('pos_id');
        return $this->db->count_all_results($this->mytable);
    }

    function num_not_in($val = '', $param = null) {
        if ($param == null)
            $param = $this->primaryKey;

        $this->db->from($this->mytable);

        if(is_array($val) && $val != array()){
            $this->db->where_not_in($param,$val);
        }
        return $this->db->count_all_results();
    }
    
    public function get_hot_posts($cat_ids, $begindate, $enddate, $days, $numpost, $start = 0) {
        $this->load->model('mlogview');
        $logIds = $this->mlogview->getListLogView($cat_ids, $numpost, $start);
        if (is_numeric($days) && $days != 0) {
            $this->db->where("p.pos_date_start >=", time() - ($days * 24 * 60 * 60));
        } else {
            $this->db->where("p.pos_date_start >=", $begindate);
            $this->db->where("p.pos_date_start <=", $enddate);
        }
        if (!$this->mlogview->check_time($enddate))
            $this->db->where('p.pos_date_start <= ' . time());

        $this->db->where('p.pos_status >0');
        
        if (count($logIds) > 0)
            $this->db->where_in('p.pos_id', $logIds);

        $posts = $this->db->get('post p', $numpost, $start)->result();
        $result = array();
        foreach ($logIds as $log) {
            foreach ($posts as $post) {
                if ($post->pos_id == $log) {
                    array_push($result, $post);
                    break;
                }
            }
        }
        return $result;
    }

    public function get_prev_next_posts($id){      
        return array(
                'prev' => $this->db->select('pos_id,pos_code,pos_title')
                                    ->where('pos_status >',0)
                                    ->where('pos_date_start <',time())
                                    ->where('pos_id <',$id)
                                    ->order_by('pos_id desc')
                                    ->limit(1)
                                    ->get($this->mytable)->first_row(),
                'next' => $this->db->select('pos_id,pos_code,pos_title')
                                    ->where('pos_status >',0)
                                    ->where('pos_date_start <',time())
                                    ->where('pos_id >',$id)
                                    ->order_by('pos_id asc')
                                    ->limit(1)
                                    ->get($this->mytable)->first_row()
            );
    }

    /*
        --------------------------------------------
        $title contains the title of the page you're sending
        $url is the url of the page
        $debug true print out the debug and show xml call and answer
        --------------------------------------------
        the output is an array with two elements:
        status: ok / ko
        msg: the text response from pingomatic
        --------------------------------------------
     */
    function pingomatic($title,$url,$debug=false) {
        $content='<?xml version="1.0"?>'.
        '<methodCall>'.
        ' <methodName>weblogUpdates.ping</methodName>'.
        '  <params>'.
        '   <param>'.
        '    <value>'.$title.'</value>'.
        '   </param>'.
        '  <param>'.
        '   <value>'.$url.'</value>'.
        '  </param>'.
        ' </params>'.
        '</methodCall>';
        
        $headers="POST / HTTP/1.0\r\n".
        "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1) Gecko/20090624 Firefox/3.5 (.NET CLR 3.5.30729)\r\n".
        "Host: rpc.pingomatic.com\r\n".
        "Content-Type: text/xml\r\n".
        "Content-length: ".strlen($content);
        
        if ($debug) nl2br($headers);
        
        $request=$headers."\r\n\r\n".$content;
        $response = "";
        $fs=fsockopen('rpc.pingomatic.com',80, $errno, $errstr);
        if ($fs) { 
            fwrite ($fs, $request); 
            while (!feof($fs)) $response .= fgets($fs); 
            if ($debug) echo "<xmp>".$response."</xmp>";
            fclose ($fs);
            preg_match_all("/<(name|value|boolean|string)>(.*)<\/(name|value|boolean|string)>/U",$response,$ar, PREG_PATTERN_ORDER);
            for($i=0;$i<count($ar[2]);$i++) $ar[2][$i]= strip_tags($ar[2][$i]);
            return array('status'=> ( $ar[2][1]==1 ? 'ko' : 'ok' ), 'msg'=>$ar[2][3] );
        } else { 
            if ($debug) echo "<xmp>".$errstr." (".$errno.")</xmp>"; 
            return array('status'=>'ko', 'msg'=>$errstr." (".$errno.")");
        } 
    }

// end count_search_results()
}

// end mpost class